package com.taotao.sso.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.pojo.TbUser;
import com.taotao.sso.service.UserService;

@Controller
public class UserController {
	@Autowired
	private UserService userService;
	@RequestMapping(value="/user/showLogin")
	public String showLogin(String redirect, Model model) {
		model.addAttribute("redirect", redirect);
		return "login";
	}
	
	@RequestMapping(value="/user/showRegister")
	public String showRegister() {
		return "register";
	}
	
	@RequestMapping(value="/user/login")
	@ResponseBody
	public TaotaoResult login(HttpServletRequest request, HttpServletResponse response, String username, String password) {
		return userService.login(request, response, username, password);
	}
	
	@RequestMapping(value="/user/register", method=RequestMethod.POST)
	@ResponseBody
	public TaotaoResult register(TbUser user) {
		return userService.register(user);
	}
	
	@RequestMapping(value="/user/check/{content}/{type}")
	@ResponseBody
	public TaotaoResult check(@PathVariable String content, @PathVariable int type) {
		if (content == null || content == "") {
			return TaotaoResult.build(400, "内容不能为空");
		}
		return userService.checkData(content, type);
	}
	@RequestMapping(value="/user/token/{token}")
	@ResponseBody
	public Object getUserByToken(@PathVariable String token, String callback) {
		TaotaoResult result = null;
		try {
			result = userService.getUserByToken(token);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = TaotaoResult.build(500, e.getMessage());
		}
		
		if (callback == null || callback == "") {
			return result;
		} else {
			MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
			mappingJacksonValue.setJsonpFunction(callback);
			return mappingJacksonValue;
			
		}
		
	}
	@RequestMapping(value="/user/logout", produces="text/html;charset=utf-8")
	@ResponseBody
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		String string = userService.logout(request, response);
		return string;
	}
}
